<template>
  <div class="m-window applyShortTable-col" v-loading="loading">
    <el-row :gutter="10" class="header-btns-col">
      <el-col :span="2">
        <el-button type="primary" @click="goBack">返回</el-button>
      </el-col>
    </el-row>
    <!-- 天进宝申请表 -->
    <el-row>
      <el-col :span="12">
        <el-form :v-model="applyShortTableForm" ref="applyShortTableForm">
          <el-form-item>
            <table class="emphasis-table">
              <tr>
                <th>流程编号：</th>
                <td class="hit font-underline">{{applyShortTableForm.item_no}}</td>
              </tr>
              <tr>
                <th>供应商名称：</th>
                <td>{{applyShortTableForm.cust_name}}</td>
              </tr>
              <tr>
                <th>收款账户户名：</th>
                <td>{{name}}</td>
              </tr>
              <tr>
                <th>收款账户账号：</th>
                <td>{{bankNo}}</td>
              </tr>
              <tr>
                <th>收款账户开户行：</th>
                <td>{{bank}}</td>
              </tr>
              <tr>
                <th>微信：</th>
                <td>{{applyShortTableForm.custSrmWechat}}</td>
              </tr>
              <tr>
                <th>邮箱：</th>
                <td>{{applyShortTableForm.custSrmEmail}}</td>
              </tr>
              <tr>
                <th>融资金额：</th>
                <td>{{getFormatApplyAmt}} 元</td>
              </tr>
              <tr>
                <th>融资产品：</th>
                <td>{{applyShortTableForm.fin_type}}</td>
              </tr>
              <tr>
                <th>融资开始日期：</th>
                <td>{{applyShortTableForm.apply_date}}</td>
              </tr>
              <tr>
                <th>融资到期日期：</th>
                <td>{{applyShortTableForm.prepayback_date}}</td>
              </tr>
              <tr>
                <th>融资天数：</th>
                <td>{{getDayAmount}}</td>
              </tr>
              <tr>
                <th>服务费率（含税）：</th>
                <td>{{showRate}}</td>
              </tr>
              <tr>
                <th>预扣服务费（含税）：</th>
                <td>{{getPreDeductAmount}} 元</td>
              </tr>
              <tr>
                <th>到账金额：</th>
                <td>{{getArrivalAmount}} 元</td>
              </tr>
              <tr>
                <th>还款金额：</th>
                <td>{{getFormatApplyAmt}} 元</td>
              </tr>
              <tr>
                <th>金融客服：</th>
                <td>{{applyShortTableForm.apply_user}}</td>
              </tr>
              <tr>
                <th>客服电话：</th>
                <td>{{applyShortTableForm.apply_phone}}</td>
              </tr>
            </table>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="23" class="checking-table">
        <label>关联对账函</label>
        <ag-grid-vue
          class="ag-theme-balham ag-table"
          :gridOptions="applyGridOptions"
          :columnDefs="applyColumnDefs"
          :rowData="applyRowData"
          v-loading="applyLoading"
        ></ag-grid-vue>
      </el-col>
    </el-row>
    <el-row v-show="fileList.length > 0" style="margin-top:20px;">
      <el-col :span="24">
        <label style="font-size: 12px;font-weight: 600;">相关附件</label>
        <ul class="accessory">
          <li v-for="(v,i) in fileList" :key="i">
            <span>{{v.name}}</span>
            <el-button plain size="mini" type="primary" @click="downloadFiles(v)">下载</el-button>
          </li>
        </ul>
      </el-col>
    </el-row>
    <el-row v-show="returnReason!=''">
      <el-col :span="23">
        <label style="color:red;">退回原因</label>
        <div class="returnReason">{{returnReason}}</div>
      </el-col>
    </el-row>
  </div>
</template>
<style>
.msg-hint .el-message-box__message p {
  text-align: left !important;
  word-break: break-all;
}
</style>

<style lang="less" scoped>
.applyShortTable-col {
  height: 100%;
  padding-top: 50px !important;
  overflow-y: auto;
  overflow-x: hidden;
  /deep/.el-button.el-button--mini {
    height: 20px !important;
    width: 50px !important;
    line-height: 20px !important;
    padding: 0 !important;
    margin-left: 20px;
  }
  .accessory {
    li {
      line-height: 25px;
      span {
        color: #409eff;
        cursor: pointer;
      }
    }
  }
  &:after {
    display: block;
    height: 100px;
    content: "";
  }
  .returnReason {
    border: 1px solid #eee;
    padding: 5px;
    min-height: 100px;
    margin-top: 5px;
  }
  .footer-btns-col,
  .header-btns-col {
    position: fixed;
    height: 60px;
    width: 100%;
    bottom: 0;
    z-index: 10;
    margin-left: -11px !important;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #fff;
    padding: 10px 0;
    border-top: 1px solid #eee;
    /deep/ .el-button {
      margin-left: -84px;
    }
  }
  .header-btns-col {
    top: 0;
    justify-content: flex-start;
    border-top: none;
    border-bottom: 1px solid #eee;
    margin-top: 100px;
    /deep/ .el-button {
      margin-left: 8px;
    }
  }
  .hit {
    color: #409eff !important;
  }
  .emphasis-table {
    width: 100%;
    margin-top: 10px;
    .font-underline {
      text-decoration: underline;
    }
    tr {
      &:nth-child(even) th,
      &:nth-child(even) td {
        background: #f9fafa;
      }
      td,
      th {
        border: 1px solid #eee;
        padding: 0 10px;
        height: 35px;
        line-height: 35px;
        text-align: right;
        width: 50%;
      }
      td {
        text-align: left;
        & /deep/.el-input {
          .el-input__inner {
            border: none !important;
            outline-style: none !important;
            height: 35px;
            line-height: 35px;
            margin-left: -10px;
          }
          .el-input__icon {
            margin-left: -10px;
            margin-top: -5px;
          }
        }
      }
    }
  }
  .checking-table {
    margin-top: -10px;
    & label {
      font-size: 12px;
      font-weight: 600;
    }
    .ag-table {
      height: 200px;
      width: 100%;
      margin-top: 8px;
    }
    .opts-col {
      float: right;
    }
  }
}
</style>
<script>
import Pagination from "@/components/pagination.vue";
import gridOptions from "lesso-common/public/gridOptions";
import downloadFile from "@/util/fileDownload.js";
import {
  formatRate,
  formatPrice,
  dateDiff,
  getSpecifyDate,
  numberMul,
  numberSub
} from "@/util/format.js";
import { mapState, mapActions } from "vuex";

export default {
  props: {
    flowNumber: String, //流程编号
    applyId: String, //申请id
    currentAct: String //现环节
  },
  data() {
    return {
      fileList: [],
      custInf: this.$store.state.supplyChainFinance.custInf, //获取供应商信息
      returnReason: "",
      loading: true,
      bankNo: "",
      bank: "",
      name: "",
      wfType: "", //流程类型，1：天进宝300万以下  2：天进宝300万以上
      applyIdFromCommit: "",
      fromPage: "",
      isSign: false,
      applyShortTableForm: {
        id: "",
        item_no: "",
        cust_name: "",
        apply_amt: 0,
        fin_type: 0,
        apply_date: "",
        dayAmount: 0,
        service_rate: 0,
        preDeductAmount: 0,
        arrivalAmount: 0,
        apply_user: "",
        apply_phone: "",
        prepayback_date: "",
        custSrmEmail: "",
        custSrmWechat: ""
      },
      applyTotal: 50,
      applyGridOptions: {},
      applyColumnDefs: [],
      applyRowData: [],
      applyLoading: false,
      pageListParams: {
        entity: {},
        current: 1,
        size: 10
      }
    };
  },
  created() {
    this.getEsignAccountByCustId();
    this.applyGridOptions = gridOptions();
    this.applyColumnDefs = [
      {
        headerName: "对账函编号",
        width: 205,
        field: "accountCode"
      },
      {
        headerName: "买方公司",
        field: "companyName",
        width: 180
      },
      {
        headerName: "商务合同名称及编号",
        field: "contractNo",
        width: 250,
        valueFormatter: params => {
          if(params.value){
              return '《' + params.data.contractName + '》' + '（编号：' + params.value + '）'
          }else{
              return ''
          }
        }
      },
      {
        headerName: "对账函月份",
        field: "letterMonth",
        width: 120
      },
      {
        headerName: "应收金额",
        field: "payBalance",
        width: 150,
        valueFormatter: params => {
          return formatPrice(params.value);
        }
      },
      {
        headerName: "可融金额",
        field: "borrowBalance",
        width: 150,
        valueFormatter: params => {
          return formatPrice(params.value);
        }
      },
      {
        headerName: "已融资金额",
        field: "finAmount",
        width: 150,
        valueFormatter: params => {
          return formatPrice(
            numberSub(
              params.node.data.payBalance,
              params.node.data.borrowBalance
            )
          );
        }
      },
      {
        headerName: "融资状态",
        field: "finStatus",
        width: 100,
        cellRenderer: function(params) {
          if (params.value != undefined && params.value == 1) {
            return "部分融资";
          } else if (params.value == 2) {
            return "已融资";
          } else {
            return "未融资";
          }
        }
      }
    ];
    this.pageListParams.entity.applyId = this.applyId;
    this.getPageLetterlist(this.pageListParams);
    this.queryAttachmentInfo();
  },
  beforeMount() {
    let that = this;
    this.fromPage = this.supplierApplyList.fromPage;
    if (this.currentAct == "已退回") {
      this.getRefusedActivity();
    }
    //获取申请主表信息
    that.$http
      .getApplyInfo({
        id: that.applyId
      })
      .then(response => {
        this.loading = false;
        if (response.data.code == 200) {
          let data = response.data.rows;
          if (data.processStatus == 0) {
            this.wfType = 1; //天进宝300万以下
          } else {
            this.wfType = 2; //天进宝300万以上
          }
          that.applyShortTableForm.id = data.id;
          that.applyShortTableForm.item_no = data.itemNo;
          that.applyShortTableForm.cust_name = data.custName;
          that.applyShortTableForm.apply_amt = data.applyAmt
            ? data.applyAmt
            : 0;
          that.applyShortTableForm.fin_type =
            data.finType == 0 ? "天进宝" : "月有钱";
          that.applyShortTableForm.service_rate = data.serviceRate
            ? data.serviceRate
            : 0;
          that.applyShortTableForm.apply_user = data.applyUser;
          that.applyShortTableForm.apply_phone = data.applyPhone;
          that.applyShortTableForm.prepayback_date = data.prepaybackDate
            ? data.prepaybackDate.substring(0, 10)
            : "";
          that.applyShortTableForm.apply_date = data.applyDate
            ? data.applyDate.substring(0, 10)
            : "";
          that.applyShortTableForm.custSrmEmail = data.custSrmEmail;
          that.applyShortTableForm.custSrmWechat = data.custSrmWechat;
        } else {
          this.$alert("获取申请表信息失败", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                });
        }
      })
      .catch(errror => {
        this.loading = false;
        this.$alert("查询主表信息失败，请检查网络", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                });
      });
  },
  methods: {
    ...mapActions(["changeTOdo", "changePageCode"]),
    ...mapActions(["changeFromPage"]),
    downloadFiles(v) {
      let path = v.lastPath;
      let fileName = `${v.name}`;
      var group = ''
        if (path.indexOf('SRM') > -1) {
          group = 'SRM'
        } else if (path.indexOf('SIGN') > -1) {
          group = 'SIGN'
        } else if (path.indexOf('TEST') > -1) {
          group = 'TEST'
        } else if (path.indexOf('MES') > -1) {
          group = 'MES'
        }
      let params = {
          'viewPath': group + `${path.split(group)[1]}`,
          'groupName':group,
          'fileName':fileName
      }
      console.log('参数',params) 
      downloadFile(params,fileName+'.pdf')
      //附件类型 0-保理服务合同 1-应收账款转让通知函 2-中登资料 3-放款审批表（短融）4-放款审批表(长融)
    //   this.$http
    //     .getFileDownload(params)
    //     .then(({ data }) => {
    //     //   if (data.code == 200) {              
    //     //     // download(fileName, data.rows[0].fileName);
    //     //   } else {
    //     //       this.$alert(data.info, {
    //     //             confirmButtonText: "确定",
    //     //             customClass: "alertFailure"
    //     //         });
    //     //   }
    //     })
    //     .catch(error => {
    //       this.$alert('下载文件失败，请检查网络！', {
    //                 confirmButtonText: "确定",
    //                 customClass: "alertFailure"
    //             });
    //     })
    },
    //查询附件列表
    async queryAttachmentInfo() {
      let param = {
        entity: {
          itemNo: this.flowNumber
        },
        current: 1,
        size: 100
      };
      await this.$http.queryAttachmentInfo(param).then(({ data }) => {
        if (data.code == 200 && data.rows) {
          this.fileList = data.rows.filter((item)=>{
            return item.type == 1 || item.type == 0
          })
        }
      });
    },
    //查询退回原因
    async getRefusedActivity() {
      await this.$http
        .getRefusedActivity({
          applyId: this.applyId
        })
        .then(({ data }) => {
          if (data.code == 200 && data.rows) {
            this.returnReason = data.rows.note || "";
          }
        })
        .catch(error => {
          this.$alert("查询退回信息数据失败，请检查网络！", {
              confirmButtonText: "确定",
              customClass: "alertFailure"
          });
        });
    },
    //主表信息
    async getEsignAccountByCustId() {
      let that = this;
      let custId = this.supplyChainFinance.custInf.custId + "";
      await this.$http
        .getEsignAccountByCustId({
          custId: custId
        })
        .then(({ data }) => {
          if (data.code == 200 && data.rows) {
            that.bankNo = data.rows.bank_no;
            var bankinfo= data.rows.sub_bank;
            bankinfo= bankinfo.replace(data.rows.bank,'');
            bankinfo = data.rows.bank + bankinfo;
            that.bank = bankinfo;
            that.name = data.rows.name;
          } else {
            this.$alert(`获取数据失败：${data.info}`, {
                confirmButtonText: "确定",
                customClass: "alertFailure"
            });
          }
        })
        .catch(error => {
           this.$alert('查询失败，请检查网络！', {
                confirmButtonText: "确定",
                customClass: "alertFailure"
            });
        });
    },
    //查询申请关联对账函
    getPageLetterlist(params) {
      this.$http
        .getApplyLetter(params)
        .then(response => {
          if (response.data.code == 200) {
            let rowDatas = response.data.rows;
            rowDatas.forEach(element => {
              element.accountNo = element.letterNo; //对账函编号
              element.accountNo = element.letterNo; //对账函编号
            });
            this.applyRowData = rowDatas;
          } else {
            this.applyRowData = [];
            this.$alert(response.data.info, {
              confirmButtonText: "确定",
              customClass: "alertFailure"
            });
          }
        })
        .catch(errror => {
          this.$alert("获取对账函信息失败，请检查网络！", {
              confirmButtonText: "确定",
              customClass: "alertFailure"
          });
          this.applyRowData = [];
        });
    },
    goBack() {
      this.changePageCode("");
    }
  },
  computed: {
    ...mapState(["supplyChainFinance", "supplierApplyList"]),
    //显示利率
    showRate() {
      return formatRate(this.applyShortTableForm.service_rate) + "/天";
    },
    //获取预扣金额
    getPreDeductAmount() {
      this.applyShortTableForm.preDeductAmount = numberMul(
        numberMul(
          this.applyShortTableForm.apply_amt,
          this.applyShortTableForm.service_rate
        ),
        this.applyShortTableForm.dayAmount
      ).toFixed(2);
      return formatPrice(this.applyShortTableForm.preDeductAmount);
    },
    getArrivalAmount() {
      this.applyShortTableForm.arrivalAmount = numberSub(
        this.applyShortTableForm.apply_amt,
        this.applyShortTableForm.preDeductAmount
      ).toFixed(2);
      return formatPrice(this.applyShortTableForm.arrivalAmount);
    },
    getDayAmount() {
      this.applyShortTableForm.dayAmount = dateDiff(
        this.applyShortTableForm.apply_date,
        this.applyShortTableForm.prepayback_date
      );
      return this.applyShortTableForm.dayAmount + "天";
    },
    getFormatApplyAmt() {
      return formatPrice(this.applyShortTableForm.apply_amt);
    }
  },
  components: {
    Pagination
  }
};
</script>